<template>
  <el-dialog title="站长设置" v-model="show" class="rounded-[15px]" width="700">
    <el-form>
      <el-form-item label="到期时间">
        <el-date-picker v-model="props.row.over_time"></el-date-picker>
      </el-form-item>
      <el-form-item label="选择账号">
        <div
          class="w-[60px] h-[60px] rounded-[10px] text-center justify-center flex flex-col"
          style="box-shadow: 0 0 10px rgb(0 0 0 / 20%)"
          @click="acceptParams"
        >
          <div v-if="!props.row.real_name" class="text-center flex justify-center cursor-pointer">
            <el-icon size="26" color="#CED1D5" class="text-center"><Upload /></el-icon>
          </div>
          <div v-else class="text-center flex justify-center cursor-pointer">
            <span>
              {{ props.row.real_name }}
            </span>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
    <siteAccount ref="accountRef" @choose="getChoose"></siteAccount>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { ref } from "vue";
import siteAccount from "./siteAccount.vue";
import { setSite } from "@/api/modules/region";
import dayjs from "dayjs";

const show = ref(false);

interface Props {
  row: any;
  getTable?: () => Promise<any>;
}

const props = ref<Props>({ row: { real_name: "", user_id: 0, over_time: new Date().getTime(), id: 0 } });

const open = (params: any) => {
  if (params.row) {
    props.value.row = JSON.parse(JSON.stringify(params.row));
  }
  props.value.getTable = params.getTable;
  show.value = true;
};

const accountRef = ref<InstanceType<typeof siteAccount> | null>();

const acceptParams = () => {
  const id = props.value.row.user_id ? props.value.row.user_id : 0;
  accountRef.value?.open(id);
};

// 获取选择用户
const getChoose = (row: any) => {
  props.value.row.real_name = row.realName;
  props.value.row.over_time = new Date().getTime();
  props.value.row.user_id = row.id;
};

// 确认
const confirm = async () => {
  if (!typeof props.value.row.over_time) return ElMessage.warning("请选择时间");
  props.value.row.over_time = new Date(props.value.row.over_time).getTime();
  if (props.value.row.over_time <= dayjs().unix()) return ElMessage.warning("时间不可小于当前时间");
  if (typeof props.value.row.user_id !== "number" && props.value.row.user_id === 0) return ElMessage.warning("请选择账号");
  try {
    await setSite({ region: props.value.row.id, id: props.value.row.user_id, over_time: props.value.row.over_time });
    ElMessage.success("成功");
    await props.value.getTable!();
    show.value = false;
  } catch (error) {}
};

defineExpose({ open });
</script>

<style></style>
